﻿
using Furion;
using Microsoft.AspNetCore.Http;
using System.IO;

namespace GSOrganization.Application;

/// <summary>
/// 人员管理
/// </summary>
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class SysPersonService : BaseService, ISysPersonService, ITransient, Furion.DynamicApiController.IDynamicApiController
{
    private RSACrypto rsaCrypto = new RSACrypto(@"MIICXAIBAAKBgQCLqzqTeRC4uoRx2R61hda7Y82RTKH2bWlgWigXaz3t337p3z47
jJ4c/klQOIY5XTcxf1n+nzyd5QdJLy7KX76Izg0MMRNg8TIzjFyQqbh6P2Hx6zqh
0N9SSIF9HvUcJ7XuzMQc1E1te0d9gLOG7pO58l3ar8UYG0t3uLnqlC64mwIDAQAB
AoGAEip3N+8rKZu41kXzJJD/2OemORvKhQ6+AfY3+LPOHj5Pd4O9yGkFt6erSW/Q
pW1mXF3ACsoTTEYZqH8mitPhKCDIwOiAlMQjezIjKJQoNXMNNKpfWaJRyjfCOWiK
ppvIw4PTep5bh+c3RvSbMvDvnwcKsj9NfZICQ3QR5krIXeECQQC1GuChUk/d53T+
+g4lLgP0WlyW4s5il4m05B8rnVrHjeOSvOEg8ACDU+DonTWnZzkYwro63RiK0/Bk
Uu063fI3AkEAxW2dScr/3/0KEPpk/GiJaotgPnqLLoIH9aDvlj07WyE3qFbOkPFc
EVLuSXTf3rPkeqaAJC+SBP/VdxRjcKlKvQJASpesZ6WQcbRwcsipZNTkGhPRyO/X
07HYrSG8WOlxx3mAfyK+kyNnArBclVKTE8UnNjSWIcKI5j1O6PNi9HkP1wJAHMmC
6cOj07E9yoP4PaWwg8yW2AVeTgW/y10QEkQTZ5JMX0tpC1FmL1B8VlGoYvywEAI/
JQearwfuxFJAvaixsQJBAKcxZUK8elewFTASWyLBDjS7fDSJ6om/tU18XJPQvD6E
KJIrtRvGx1LB6CHvJQ1NiPNQkTqZLIQLRu9KRf9nPD4=", @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLqzqTeRC4uoRx2R61hda7Y82R
TKH2bWlgWigXaz3t337p3z47jJ4c/klQOIY5XTcxf1n+nzyd5QdJLy7KX76Izg0M
MRNg8TIzjFyQqbh6P2Hx6zqh0N9SSIF9HvUcJ7XuzMQc1E1te0d9gLOG7pO58l3a
r8UYG0t3uLnqlC64mwIDAQAB");
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IRepository<SysMenu> _sysMenu;
    private readonly IRepository<SysRole> _sysRole;
    private readonly IRepository<SysDepartment> _sysdepartment;
    private readonly IRepository<SysPerson> _repository;
    private readonly string _menuName = "人员管理";

    public SysPersonService(IHttpContextAccessor httpContextAccessor,IRepository<SysPerson> repository, IRepository<SysDepartment> sysdepartment,
     IRepository<SysMenu> sysMenu,
     IRepository<SysRole> sysRole)
    {
        _httpContextAccessor = httpContextAccessor;
        _sysMenu = sysMenu;

        _sysRole = sysRole;

        _repository = repository;

        _sysdepartment = sysdepartment;
    }

    /// <summary>
    /// 修改、添加用户
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    [HttpPost]
    public ResponseModel Setting(SysPersonSettingInput entity)
    {
        var item = _repository.Include(i => i.SysRole).FirstOrDefault(w => w.IsDel == false && w.Id == UserId);


        if (UserName != entity.LoginName)
        {
            if (GetByLoginName(entity.LoginName))
            {
                return ResponseModel.Fail("用户名已经被占用");

            }

        }
        entity.Adapt(item);

        _repository.SaveNow();

        return ResponseModel.Succeed(); ;
    }
    public SysPersonSettingInput SettingSysPerson()
    {

        var item = _repository.FirstOrDefault(w => w.IsDel == false && w.Id == UserId);
        var entity = item.Adapt<SysPersonSettingInput>();

        return entity;
    }
    /// <summary>
    /// 获取单个实体
    /// </summary> 
    /// <param name="id">主键</param>
    /// <returns></returns>    
    public SysPersonOutput GetSysPerson(string id)
    {
        if (string.IsNullOrWhiteSpace(id))
        {
            return null;
        }
        var item = _repository.Include(i => i.SysRole).FirstOrDefault(w => w.IsDel == false && w.Id == id);
        var entity = item.Adapt<SysPersonOutput>();

        //foreach (var it in item.SysRole)
        //{
        //    entity.SysRoles.Add(it.Id);
        //}

        return entity;
    }
    /// <summary>
    /// 通过名字获取人员
    /// </summary>
    /// <param name="id">主键</param>
    /// <returns>外键实体集合</returns>
    public bool GetByLoginName(string id)
    {
        return _repository.Any(w => w.IsDel == false && w.LoginName == id);
    }
    /// <summary>
    /// 列表
    /// </summary>
    /// <param name="param">列表的参数对象</param>
    /// <returns>列表返回值</returns>
    public ResponseModel<List<SysPersonIndexOutput>> DataSysPerson(SysPersonIndexInput param)
    {


        var data = _repository.Include(i => i.SysRole).AsQueryable();
        data = data.Where(w => w.IsDel == false);

        if (!string.IsNullOrWhiteSpace(param.LoginName))
        {
            data = data.Where(a => a.Name.Contains(param.LoginName)
            || a.LoginName.Contains(param.LoginName)
            || a.DepartmentName.Contains(param.LoginName)
            || a.ContactPhone.Contains(param.LoginName));
        }

        var result = data.OrderByDescending(o => o.CreatedTime)
              .Skip((param.Page - 1) * param.Limit)
              .Take(param.Limit)
              .Select(s => new SysPersonIndexOutput
              {
                  Id = s.Id,
                  LoginName = s.LoginName,
                  DepartmentName = s.DepartmentName,
                  Code = s.Code,
                  Address = s.Address,
                  Roles = string.Join("，", s.SysRole.Select(o => o.Name)),
                  Representative = s.Representative,
                  ContactPerson = s.ContactPerson,
                  ContactPhone = s.ContactPhone,

              });

        var total = data.Count();

        return new ResponseModel<List<SysPersonIndexOutput>>
        {
            count = total,
            data = result.ToList()
        };

    }
    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="entity">一个实体</param>
    /// <returns>是否成功</returns>
    [Microsoft.AspNetCore.Mvc.HttpPost]
    public ResponseModel CreateSysPerson(SysPersonInput entity)
    {

        if (string.IsNullOrWhiteSpace(entity.Id))
        {
            //创建
            //校验
            if (string.IsNullOrWhiteSpace(entity.Password) || string.IsNullOrWhiteSpace(entity.SurePassword))
            {
                return ResponseModel.Fail("密码和确认密码不为空");
            }
            if (entity.Password.Length < 8)
            {
                return ResponseModel.Fail("密码不能小于8位");
            }
            if (entity.Password != entity.SurePassword)
            {
                return ResponseModel.Fail("密码和确认密码不一致");
            }
            if (GetByLoginName(entity.LoginName))
            {
                return ResponseModel.Fail("用户名已经被占用");
            }

            var item = entity.Adapt<SysPerson>();
            item.Password = EncryptAndDecrypte.EncryptString(entity.Password);
            item.SurePassword = string.Empty;
            item.State = "开启";
            item.Id = Result.GetNewId();
            item.CreateUserId = UserId;


            if (entity.SysRoles != null && entity.SysRoles.Count > 0)
            {
                foreach (var addItem in entity.SysRoles)
                {
                    SysRole sr = new SysRole() { Id = addItem.Id };

                    _repository.Attach(sr);
                    item.SysRole.Add(sr);
                }

            }

            _repository.Insert(item);
            var ds = _repository.SaveNow();

            var log = new SysLogInput() { Result = "成功", MenuId = _menuName, Message = "新增人员，" + item.Name };
            LogModels.WriteLog(log);

            return ResponseModel.Succeed(ds);
        }
        else
        {
            //修改

            var item = _repository.Include(i => i.SysRole).FirstOrDefault(f => f.Id == entity.Id);
            if (item == null)
            {
                throw Oops.Oh("数据不存在");

            }
            //校验
            if (item.LoginName != (entity.LoginName) && GetByLoginName(entity.LoginName))
            {
                return ResponseModel.Fail("用户名已经被占用");
            }
            //多对多关系，先删除后新增
            /*                       
                           * 不操作 原有 现有
                           * 增加   原没 现有
                           * 删除   原有 现没
                           */

            if (item.SysRole != null && entity.SysRoles != null)
            {

                var now = entity.SysRoles.Select(s => s.Id);
                var old = item.SysRole.Select(s => s.Id);
                // 不操作 原有 现有
                var both = old.Intersect(now);//获取不同集合的相同项（交集）
                //删除   原有 现没
                var delete = old.Except(both);//Except - 从某集合中删除其与另一个集合中相同的项；其实这个说简单点就是某集合中独有的元素
                foreach (var deleteItem in delete)
                {

                    item.SysRole.Remove(item.SysRole.FirstOrDefault(f => f.Id == deleteItem));

                }
                //增加   原没 现有
                var add = now.Except(both);
                foreach (var addItem in add)
                {
                    SysRole sr = new SysRole() { Id = addItem };

                    _repository.Attach(sr);
                    item.SysRole.Add(sr);
                }
            }

            entity.Password = item.Password;
            entity.Adapt(item);

            //if (item.SysRole != null && item.SysRole.Count > 0)
            //{
            //    foreach (var it in item.SysRole.Distinct())
            //    {
            //        _repository.Attach(it);

            //    }

            //}

            item.UpdateUserId = UserId;
            var ds = _repository.SaveNow();

            var log = new SysLogInput() { Result = "成功", MenuId = _menuName, Message = "人员信息修改，" + item.Name };
            LogModels.WriteLog(log);

            return ResponseModel.Succeed(ds);
        }


    }


    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="entity">一个实体</param>
    /// <returns>是否成功</returns>
    [Microsoft.AspNetCore.Mvc.HttpPost]
    [AllowAnonymous]
    public ResponseModel Register(RegisterInput entity)
    {
        if (string.IsNullOrWhiteSpace(entity.Password) || string.IsNullOrWhiteSpace(entity.SurePassword))
        {
            return ResponseModel.Fail("密码和确认密码不为空");
        }
        if (entity.Password.Length < 8)
        {
            return ResponseModel.Fail("密码不能小于8位");
        }
        if (entity.Password != entity.SurePassword)
        {
            return ResponseModel.Fail("密码和确认密码不一致");
        }


        var password = EncryptAndDecrypte.EncryptString(entity.Password);

        //主表
        var item = entity.Adapt<SysPerson>();
        item.Password = password;

        item.State = "开启";

        SysRole sr = new SysRole() { Id = "worker" };

        _repository.Attach(sr);
        item.SysRole.Add(sr);
        _repository.Insert(item);

        var ds = _repository.SaveNow();

        var log = new SysLogInput() { Result = "成功", MenuId = _menuName, Message = "注册，" + item.LoginName };
        LogModels.WriteLog(log);
        //自动登录
        LoginInput param = new LoginInput();
        param.PassWord = rsaCrypto.Encrypt(entity.Password);
        param.LoginName = rsaCrypto.Encrypt(entity.LoginName);
        Login(param);

        return ResponseModel.Succeed();
    }
    /// <summary>
    /// 数据初始化,注册的用户角色增加
    /// </summary> 
    /// <returns>是否成功</returns>
    [Microsoft.AspNetCore.Mvc.HttpGet]
    [AllowAnonymous]
    public ResponseModel SetInitializer()
    {

        var can = _repository.Database.EnsureCreated();
        if (can)
        {

            var item = _repository.FirstOrDefault();
            if (item == null)
            {
                SysDepartment department = new SysDepartment() { Id = "1", Name = "公司" };

                //"三员"指：系统管理员、安全保密管理员和安全审计员
                SysPerson personManager = new SysPerson()
                {
                    State = "开启",
                    SysDepartment = department,
                    Id = "1",
                    Name = "系统管理员",
                    LoginName = "manager",
                    Password = EncryptAndDecrypte.EncryptString("www.yiruanzhu.cn")
                };

                //SysPerson personSecrecy = new SysPerson()
                //{
                //    State = "开启",
                //    SysDepartment = department,
                //    Id = "2",
                //    Name = "安全保密管理员",
                //    LoginName = "secrecy",
                //    Password = EncryptAndDecrypte.EncryptString("Tengfei12?")
                //};

                //SysPerson personAuditor = new SysPerson()
                //{
                //    State = "开启",
                //    SysDepartment = department,
                //    Id = "3",
                //    Name = "安全审计员",
                //    LoginName = "auditor",
                //    Password = EncryptAndDecrypte.EncryptString("Tengfei12?")
                //};
                //SysPerson ACGN = new SysPerson()
                //{//Animation（动画）、Comic（漫画）、Game（游戏）、Novel（小说），上线记得删除
                //    State = "开启",
                //    SysDepartment = department,
                //    Id = "4",
                //    Name = "ACGN",
                //    LoginName = "ACGN",
                //    Password = EncryptAndDecrypte.EncryptString("Tengfei12?")
                //};

                SysMenu menuRight = new SysMenu() { Id = "11", Title = "权限管理", Href = "", Icon = "fa fa-address-book", Sort = 11 };
                SysMenu menuSysPerson = new SysMenu() { Parent = menuRight, Id = "111", Title = "用户管理", Href = "SysPerson", Icon = "fa fa-address-book", Sort = 111 };
                SysMenu menuSysRole = new SysMenu() { Parent = menuRight, Id = "222", Title = "角色管理", Href = "SysRole", Icon = "fa fa-list-ul", Sort = 222 };
                SysMenu menuSysLog = new SysMenu() { Parent = menuRight, Id = "333", Title = "日志管理", Href = "SysLog", Icon = "fa fa-address-book", Sort = 333 };

                SysMenu menuSysDepartment = new SysMenu() { Parent = menuRight, Id = "444", Title = "菜单管理", Href = "SysMenu", Icon = "fa fa-th-list", Sort = 444 };

                SysMenuSysRoleSysOperation menurolemanagerdepartment = new SysMenuSysRoleSysOperation() { Id = "11", SysMenu = menuSysDepartment };
                SysMenuSysRoleSysOperation menurolemanagerrole = new SysMenuSysRoleSysOperation() { Id = "22", SysMenu = menuSysRole };
                SysMenuSysRoleSysOperation menurolemanagerperson = new SysMenuSysRoleSysOperation() { Id = "33", SysMenu = menuSysPerson };
                SysMenuSysRoleSysOperation menurolesecrecy = new SysMenuSysRoleSysOperation() { Id = "44", SysMenu = menuSysRole };
                SysMenuSysRoleSysOperation menuroleauditor = new SysMenuSysRoleSysOperation() { Id = "55", SysMenu = menuSysLog };


                //系统管理员对组织机构，角色以及用户具有管理权限，能够进行新建、编辑、删除等操作，“三员”及属于“三员”的角色不在权限范围之内。同时，系统管理员仅进行操作管理，无法为角色配置权限。
                SysRole manager = new SysRole() { Id = "manager", Name = "系统管理员" };
                manager.SysPerson.Add(personManager);
                //manager.SysPerson.Add(ACGN);

                manager.SysMenuSysRoleSysOperation.Add(menurolemanagerdepartment);
                manager.SysMenuSysRoleSysOperation.Add(menurolemanagerrole);
                manager.SysMenuSysRoleSysOperation.Add(menurolemanagerperson);
                //安全保密员能够对角色及用户的权限进行管理，即能够给所有角色添加或移除用户，并设置普通用户权限，“三员”角色除外。同时安全保密员也将对系统管理员及安全审计员的操作进行监督。
                SysRole secrecy = new SysRole() { Id = "secrecy", Name = "安全保密管理员" };
               // secrecy.SysPerson.Add(personSecrecy);
               // secrecy.SysPerson.Add(ACGN);
                secrecy.SysMenuSysRoleSysOperation.Add(menurolesecrecy);

                //安全审计员主要负责查看其它两员的操作日志并进行监督。但无法对日志进行编辑及更改。
                SysRole auditor = new SysRole() { Id = "auditor", Name = "安全审计员" };
               // auditor.SysPerson.Add(personAuditor);
               // auditor.SysPerson.Add(ACGN);
                auditor.SysMenuSysRoleSysOperation.Add(menuroleauditor);

                //注册的用户
                SysRole worker = new SysRole() { Id = "worker", Name = "注册用户" };
                worker.SysMenuSysRoleSysOperation.Add(menuroleauditor);



                _sysRole.Insert(manager);
                //_sysRole.Insert(secrecy);
                //_sysRole.Insert(auditor);
                _sysRole.Insert(worker);

                var ds = _repository.SaveNow();

                var log = new SysLogInput() { Result = "成功", MenuId = "人员管理", Message = "数据初始化" };
                LogModels.WriteLog(log);

            }
            else
            {
                return ResponseModel.Fail("对不起，人员表已经存在数据");
            }

        }

        return ResponseModel.Succeed();
    }
    /// <summary>
    /// 执行txt的sql内容
    /// </summary> 
    /// <returns>是否成功</returns>
    [Microsoft.AspNetCore.Mvc.HttpGet]
    [AllowAnonymous]
    public ResponseModel SetInsert()
    { 
        var port = App.HttpContext.Request.Host.Port;
        string m_Line = string.Empty;
        var path = @"C:\wwwroot\yiruanzhu808\wwwroot\autoCodes\" + port;
        using (StreamReader sr = new StreamReader(path+".txt", System.Text.Encoding.UTF8))
        {
            StringBuilder index = new StringBuilder();
            while ((m_Line = sr.ReadLine()) != null)
            {
                index.Append(m_Line).Append("\r\n");
            }
            sr.Close();
              
            _repository.SqlNonQuery(index.ToString());
            var newFilePath = path;
            File.Move(path + ".txt", path + "delete.txt");

        }
       
         

        return ResponseModel.Succeed();
    }
    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public ResponseModel DeleteSysPerson(string id)
    {
        if (!string.IsNullOrWhiteSpace(id))
        {

            var item = _repository.FirstOrDefault(a => a.Id == id);
            if (item != null)
            {
                if (item.LoginName == "manager" || item.LoginName == "secrecy" || item.LoginName == "auditor")
                {
                    var sdaf = UserId;
                    var log = new SysLogInput() { Result = "成功", MenuId = "人员管理", Message = "三员账户无法删除" + item.Name + ",id为" + id };
                    LogModels.WriteLog(log);
                    return ResponseModel.Fail("对不起，三员账户无法删除。");
                }
                else
                {

                    item.IsDel = true;
                    item.UpdateUserId = UserId;
                    item.UpdatedTime = DateTime.Now;

                    _repository.UpdateNow(item);


                    var log = new SysLogInput() { Result = "成功", MenuId = "人员管理", Message = "删除" + item.Name + ",id为" + id };
                    LogModels.WriteLog(log);

                }
            }
            else
            {
                return ResponseModel.Fail("对不起，删除的数据不存在");
            }


        }
        else
        {
            return ResponseModel.Fail("主键不能为空");
        }

        return ResponseModel.SucceedDelete();
    }
    /// <summary>
    /// 重置密码
    /// </summary> 
    /// <param name="id">主键</param>
    /// <returns></returns>    
    public ResponseModel ResetSysPerson(string id)
    {
        if (!string.IsNullOrWhiteSpace(id))
        {

            var item = _repository.FirstOrDefault(a => a.Id == id);
            if (item != null)
            {
                item.Password = EncryptAndDecrypte.EncryptString("Keyan2022?");
                item.UpdateUserId = UserId;
                item.UpdatedTime = DateTime.Now;

                _repository.UpdateNow(item);
                var log = new SysLogInput() { Result = "成功", MenuId = _menuName, Message = "重置密码" + item.Name + ",id为" + id };
                LogModels.WriteLog(log);
            }
            else
            {
                return ResponseModel.Fail("对不起，当前数据不存在");
            }

        }
        else
        {
            return ResponseModel.Fail("主键不能为空");
        }

        return new ResponseModel();
    }
    /// <summary>
    /// 获取用户
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public MyCurrentUser GetCurrentUser(LoginInput param)
    {
        if (PasswordStrength(param.PassWord) != Strength.Strong)
        {
            return null;
        }


        var password = EncryptAndDecrypte.EncryptString(param.PassWord);

        var person = _repository.Include(i => i.SysRole).FirstOrDefault(p => p.LoginName == param.LoginName && p.Password == password  && true == p.IsDel);
        if (person != null)
        {
            MyCurrentUser mycurrent = new MyCurrentUser();
            mycurrent.UserName = person.LoginName;
            mycurrent.Name = person.ContactPerson;

            mycurrent.Id = person.Id;
            var role = person.SysRole.Select(s => s.Name);
            if (role != null)
            {
                mycurrent.RoleName = string.Join(",", role);
            }

            mycurrent.DepartmentName = person.DepartmentName;
            mycurrent.DepartmentId = person.SysDepartmentId;
            //生成 token
            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {
                { "UserId", mycurrent.Id },  // 存储Id
                { "UserName",mycurrent.UserName }, // 存储用户名
                { "Name",mycurrent.Name }, // 存储用户名
                { "RoleName",mycurrent.RoleName }, // 存储用户权限
                { "DepartmentId",mycurrent.DepartmentId }, // 存储用户单位Id
                { "DepartmentName",mycurrent.DepartmentName }, // 存储用户单位名称
                  
            });

            mycurrent.Token = accessToken;

            var log = new SysLogInput() { Name = param.LoginName, Result = "成功", MenuId = "登录", Message = "登录用户名为：" + mycurrent.Id };
            LogModels.LoginWriteLog(log);

            return mycurrent;
        }
        else
        {
            var log = new SysLogInput() { Name = param.LoginName, Result = "失败", MenuId = "登录", Message = "登录密码为：" + param.PassWord };
            LogModels.LoginWriteLog(log);

            return null;
        }
    }
    [HttpPost]
    [AllowAnonymous]
    public ResponseModel Login(LoginInput param)
    {
        if (param == null)
        {
            return ResponseModel.Fail("对象不存在");

        }
        param.LoginName = rsaCrypto.Decrypt(param.LoginName);
        param.PassWord = rsaCrypto.Decrypt(param.PassWord);

        if (PasswordStrength(param.PassWord) != Strength.Strong)
        {
            return ResponseModel.Fail("密码需要更复杂");

        }


        var mycurrent = GetCurrentUser(param);

        if (mycurrent == null)
        {
            return ResponseModel.Fail("不成功");
        }
        return ResponseModel.Succeed(new LoginModelOutput { UserName = mycurrent.UserName, Id = mycurrent.Id });
    }
    /// <summary>
    /// 密码强度
    /// </summary>
    private enum Strength
    {
        Invalid = 0, //无效密码
        Weak = 1, //低强度密码
        Normal = 2, //中强度密码
        Strong = 3 //高强度密码
    };
 
    private static Strength PasswordStrength(string password)
    {
        return Strength.Strong;//以后要放开liutengfei
        // 计算密码强度   <p>1.密码长度为8-128位之间</p>
        //       <p>2.必须包含数字、大小写字母和特殊符号</p>
        //         <p>3.键盘上连续字符不能超过3位</p>
        //         <p>4.连续或重复字母不能大于等于3位</p>
        //        <p>5.连续或重复数字不能大于等于3位</p>

        //空字符串强度值为0
        if (string.IsNullOrWhiteSpace(password)) return Strength.Invalid;
        //字符统计
        int iNum = 0, iLtt = 0, iSym = 0;
        foreach (char c in password)
        {
            if (c >= '0' && c <= '9') iNum++;
            else if (c >= 'a' && c <= 'z') iLtt++;
            else if (c >= 'A' && c <= 'Z') iLtt++;
            else iSym++;
        }
        if (iLtt == 0 && iSym == 0) return Strength.Weak; //纯数字密码
        if (iNum == 0 && iLtt == 0) return Strength.Weak; //纯符号密码
        if (iNum == 0 && iSym == 0) return Strength.Weak; //纯字母密码
        if (password.Length > 128) return Strength.Weak; //长度大于128的密码
        if (iLtt == 0) return Strength.Normal; //数字和符号构成的密码
        if (iSym == 0) return Strength.Normal; //数字和字母构成的密码
        if (iNum == 0) return Strength.Normal; //字母和符号构成的密码
        if (password.Length < 8) return Strength.Normal; //长度不大于8的密码
        return Strength.Strong; //由数字、字母、符号构成的密码
    }
    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="entity">修改密码的模型</param>
    /// <returns></returns>
    public ResponseModel ChangePassword(ChangePasswordInput entity)
    {
        if (entity.ConfirmPassword != entity.NewPassword)
        {
            return ResponseModel.Fail("对不起，两次输入的密码不一致");
        }
        if (PasswordStrength(entity.NewPassword) != Strength.Strong)
        {
            return ResponseModel.Fail("对不起，密码需要更复杂");
           
        }

        string oldPasswordEncryptString = EncryptAndDecrypte.EncryptString(entity.OldPassword);
        string newPasswordEncryptString = EncryptAndDecrypte.EncryptString(entity.NewPassword);

        var item = _repository.FirstOrDefault(p => p.Id == UserId && p.Password == oldPasswordEncryptString && true == p.IsDel);

        if (item != null)
        {
            if (item.State != "开启")
            {
                return ResponseModel.Fail("账号已经禁用，请联系管理员");

            }
            //验证成功
            item.Password = newPasswordEncryptString;
            item.SurePassword = newPasswordEncryptString;
            item.UpdatedTime = DateTime.Now;
            item.UpdateUserId = UserId;
            _repository.UpdateNow(item);
            //发送通知的邮件
            var log = new SysLogInput() { Result = "成功", MenuId = _menuName, Message = "密码密码成功。" + item.Name };
            LogModels.WriteLog(log);

            return new ResponseModel();
        }
        else
        {
            return ResponseModel.Fail("旧密码不正确");



        }
    }
}



